import React, { useState, useEffect } from "react";

import type { CollapseProps } from "antd";

import {
  Collapse,
  Divider,
  Flex,
  Tag,
  Button,
  Modal,
  Input,
  Table,
  Form,
  Space,
  InputNumber,
  Select,
  message,
} from "antd";
import {
  getMsg,
  addMsg,
  getOrderList,
  dictType,
  saveType,
  deleteType,
  employeeUserSave,
  employeeUserList,
  employeeUserRemove,
} from "@/api";

const colorArr = [
  "processing",
  "success",
  "error",
  "warning",
  "magenta",
  "red",
  "volcano",
  "orange",
];

const columns = (del: any, handleUpdate: any,handleEdit:any) => [
  {
    title: "姓名",
    dataIndex: "name",
    key: "name",
  },

  {
    title: "年龄",
    dataIndex: "age",
    key: "age",
  },
  {
    title: "状态",
    dataIndex: "statusStr",
    key: "statusStr",
  },
  {
    title: "注册来源",
    dataIndex: "fromUser",
    key: "fromUser",
  },
  {
    title: "住址",
    dataIndex: "address",
    key: "address",
  },
  {
    title: "电话",
    dataIndex: "phone",
    key: "phone",
  },
  {
    title: "操作",
    dataIndex: "id",
    key: "id",
    render: (v, r) => {
      return (
        <div>
          <Button type="link" onClick={() => handleEdit(r)}>
            编辑
          </Button>
          {r.status === 0 && (
            <>
              <Button type="link" onClick={() => handleUpdate(r)}>
                启用
              </Button>
            </>
          )}
          {r.status === 1 && (
            <>
              <Button type="link" onClick={() => handleUpdate(r)}>
                禁用
              </Button>
            </>
          )}
          <Button type="link" onClick={() => del(v)}>
            删除
          </Button>
        </div>
      );
    },
  },
];

export default function whiteConfig() {
  const [form] = Form.useForm();
  const [form1] = Form.useForm();

  const [clouthVal, setClouthVal] = useState("");

  const [campanyVal, setCampanyVal] = useState("");

  const [clothing, setClothing] = useState([
    { name: "衣服" },
    { name: "裤子" },
    { name: "鞋子" },
    { name: "袜子" },
  ]);

  const [campanyData, setCampanyData] = useState([]);

  const [clothData, setClothData] = useState([]);

  const [dataSource, setDataSource] = useState({
    records: [],
    pageNumber: 1,
    pageSize: 10,
    totalRow: 0,
  });

  const [selectId, setSelectId] = useState('');
  

  useEffect(() => {
    getCampanyData("GS");
    getCampanyData("FSLX");
  }, []);

  const handleEdit = (r) =>{
    setSelectId(r.id);
    form1.setFieldsValue({...r})
    setisShow_c(true)
  };

  const getCampanyData = (code) => {
    dictType({ categoryCode: code, pageIndex: 1, pageSize: 999 }).then(
      (data) => {
        console.log(data, "datadata111");
        if (data?.status) {
          if (code === "GS") {
            setCampanyData(
              data?.data?.records?.map((item) => {
                return { name: item.value, id: item.id };
              })
            );
          } else if (code === "FSLX") {
            const arr = data?.data?.records?.map((item) => {
              return { name: item.value, id: item.id };
            });
            setClothData(arr);
          }
        } else {
          message.error(data?.msg || data?.code || "请求错误");
        }
      }
    );
  };

  const deleteFun = (id: any) => {
    Modal.warning({
      title: "删除",
      content: "确认删除吗？删除后不可还原。",
      onOk: () => {
        employeeUserRemove(id).then((data) => {
          if (data?.status) {
            message.success("删除成功");
            getEmployeeList({
              pageNumber: dataSource.pageNumber,
              pageSize: dataSource.pageSize,
            });
          } else {
            message.error(data?.msg || data?.code || "请求错误");
          }
        });
      },
    });
  };

  const handleUpdate = (values: any, type: string) => {
    let params = { id: values.id,
      status: values.status === 0 ? 1 : 0,
      statusStr: values.status === 0 ? "正常" : "禁用",};
    // if (type === "startEnd") {
    //   params = {
    //     id: values.id,
    //     status: values.status === 0 ? 1 : 0,
    //     statusStr: values.status === 0 ? "正常" : "禁用",
    //   };
    // } else {
    //   params = {
    //     id: values.id,
    //     status: values.status === 0 ? 1 : 0,
    //     statusStr: values.status === 0 ? "正常" : "禁用",
    //   };
    // }
    employeeUserSave(params).then((res) => {
      const { data, status, msg } = res;
      if (status === 200 && data) {
        // setVisible(true);
        message.success("更新成功");
        getEmployeeList({
          pageNumber: dataSource.pageNumber,
          pageSize: dataSource.pageSize,
        });
        form.resetFields();
        close();

        return;
      } else {
        message.error(msg || "更新失败！");
      }
    });
  };

  const deleteCampanyData = (code, val) => {
    deleteType({ categoryCode: code, id: val }).then((data) => {
      if (data?.status) {
        if (code === "GS") {
          // console.log(data?.data?.records?.map((item) => item.value));

          // setCampanyData(data?.data?.records?.map((item) => item.value));
          getCampanyData("GS");
        } else if (code === "FSLX") {
          // const arr = data?.data?.records?.map((item) => item.value);
          // setClothData(arr);
          getCampanyData("FSLX");
        }
      } else {
        message.error(data?.msg || data?.code || "请求错误");
      }
    });
  };

  const items: CollapseProps["items"] = [
    {
      key: "1",
      label: "服饰类型",
      children: (
        <>
          <Button type="primary" onClick={() => setisShow(true)}>
            新增
          </Button>
          <Divider />
          <Flex gap="4px 0" wrap>
            {clothData?.map((item, i) => (
              <Tag
                key={i}
                bordered={false}
                color={colorArr[i]}
                closable
                onClose={(e) => {
                  e.preventDefault();
                  Modal.warning({
                    title: "删除",
                    content: "确认删除吗？删除后不可还原。",
                    onOk: () => {
                      handleClose(item.id);
                    },
                  });
                }}
              >
                {item.name}
              </Tag>
            ))}
          </Flex>
        </>
      ),
    },

    {
      key: "2",
      label: "公司分类",
      children: (
        <>
          <Button type="primary" onClick={() => addCampny()}>
            新增
          </Button>
          <Divider />
          <Flex gap="4px 0" wrap>
            {campanyData?.map((item, i) => (
              <Tag
                key={i}
                // bordered={false}
                // color={colorArr[i]}
                closable
                onClose={(e) => {
                  e.preventDefault();
                  Modal.warning({
                    title: "删除",
                    content: "确认删除吗？删除后不可还原。",
                    onOk: () => {
                      handleCloseCampany(item.id);
                    },
                  });
                }}
              >
                {item.name}
              </Tag>
            ))}
          </Flex>
        </>
      ),
    },

    {
      key: "3",
      label: "人员白名单",
      children: (
        <>
          <Button type="primary" onClick={() => setisShow_b(true)}>
            新增
          </Button>
          <Divider />
          <Table
            dataSource={dataSource.records || []}
            columns={columns(deleteFun, handleUpdate,handleEdit)}
            pagination={{
              total: dataSource.totalRow,
              showSizeChanger: true,
              onChange: (pageNo, pageSize) => {
                setDataSource({ ...dataSource, pageNumber: pageNo, pageSize });
              },
            }}
          />
        </>
      ),
    },
  ];

  const onChange = (key: string | string[]) => {
    console.log(key);
  };

  const addCloth = () => {
    console.log(clouthVal, "clouthVal");
    saveType({
      code: clouthVal,
      value: clouthVal,
      categoryCode: "FSLX",
      categoryName: "FSLX",
    }).then((data) => {
      getCampanyData("FSLX");
      setisShow(false);
    });
  };

  const addCampny1 = () => {
    saveType({
      code: campanyVal,
      value: campanyVal,
      categoryCode: "GS",
      categoryName: "GS",
    }).then((data) => {
      getCampanyData("GS");
      setisShow_a(false);
    });
  };

  const addCampny = () => {
    setisShow_a(true);
  };

  const addPerson = () => {
    // Modal.confirm({
    //   title: "新增人员",
    //   footer: false,
    //   content: (
    //     <>
    //       <Form
    //         form={form}
    //         name="validateOnly"
    //         layout="vertical"
    //         autoComplete="off"
    //       >
    //         <Form.Item name="name" label="姓名" rules={[{ required: true }]}>
    //           <Input />
    //         </Form.Item>
    //         <Form.Item name="age" label="年龄" rules={[{ required: true }]}>
    //           <InputNumber min={1} max={100} />
    //         </Form.Item>
    //         <Form.Item name="sex" label="性别" rules={[{ required: true }]}>
    //           <Select
    //             options={[
    //               { label: "男", value: "male" },
    //               { label: "女", value: "female" },
    //             ]}
    //           />
    //         </Form.Item>
    //         <Form.Item
    //           name="phoneNum"
    //           label="电话号码"
    //           rules={[{ required: true }]}
    //         >
    //           <Input />
    //         </Form.Item>
    //         <Form.Item
    //           name="phoneNum"
    //           label="岗位"
    //           rules={[{ required: true }]}
    //         >
    //           <Input />
    //         </Form.Item>
    //         <Form.Item>
    //           <Space>
    //             <Button
    //               onClick={() => {
    //                 handleAdd();
    //               }}
    //             >
    //               确认
    //             </Button>
    //             <Button htmlType="reset">取消</Button>
    //           </Space>
    //         </Form.Item>
    //       </Form>
    //     </>
    //   ),
    //   okText: "确认",
    //   // onOk: () => {
    //   //   console.log('aaaa');
    //   // },
    // });
  };

  const handleAdd = (type) => {
    // setVisible(true);
    try {
      form?.validateFields().then((values) => {
        let params = {
          ...values,
          fromUser: "后台",
          status: 1,
          statusStr: "正常",
        };
        employeeUserSave(params).then((res) => {
          const { data, status, msg } = res;
          if (status === 200 && data) {
            // setVisible(true);
            message.success("成功");
            getEmployeeList({
              pageNumber: dataSource.pageNumber,
              pageSize: dataSource.pageSize,
            });
            form.resetFields();
            form1.resetFields();
            close();

            return;
          } else {
            message.error(msg || "失败！");
          }
        });
      });
    } catch (error) {
      console.log(error);
    }
  };

  const handleAdd2 = (type) => {
    // setVisible(true);
    try {
      form1?.validateFields().then((values) => {
        console.log(values);
        let params = {
          id:selectId,
          ...values
        };
        employeeUserSave(params).then((res) => {
          const { data, status, msg } = res;
          if (status === 200 && data) {
            // setVisible(true);
            message.success("成功");
            getEmployeeList({
              pageNumber: dataSource.pageNumber,
              pageSize: dataSource.pageSize,
            });
            form1.resetFields();
            close();

            return;
          } else {
            message.error(msg || "失败！");
          }
        });
      });
    } catch (error) {
      console.log(error);
    }
  };

  // 获取人员列表
  const getEmployeeList = (params) => {
    employeeUserList({ ...params }).then((res) => {
      const { data, status, msg } = res;
      console.log(status, data);
      if (status) {
        setDataSource(data);
      } else {
        message.error(msg || "获取数据失败！");
      }
    });
  };

  useEffect(() => {
    getEmployeeList({
      pageNumber: dataSource.pageNumber,
      pageSize: dataSource.pageSize,
    });
  }, [dataSource.pageNumber, dataSource.pageSize]);

  const handleClose = (v) => {
    deleteCampanyData("FSLX", v);
    getCampanyData("FSLX");
    // console.log(v, "vvv");
    // Modal.warning({
    //   title: "删除",
    //   content: "确认删除吗？删除后不可还原。",
    //   onOk: () => {
    //     deleteCampanyData('FSLX',v)

    //   },
    // });
  };

  const handleCloseCampany = (v) => {
    deleteCampanyData("GS", v);
    getCampanyData("GS");
  };

  const close = () => {
    // console.log(v, "vvv");
    setisShow(false);
    setisShow_a(false);
    setisShow_b(false);
    setisShow_c(false);
  };

  const [isShow, setisShow] = useState(false);
  const [isShow_a, setisShow_a] = useState(false);
  const [isShow_b, setisShow_b] = useState(false);
  const [isShow_c, setisShow_c] = useState(false);

  return (
    <>
      <Collapse
        items={items}
        defaultActiveKey={["1", "2", "3"]}
        onChange={onChange}
      />

      <Modal
        maskClosable={false}
        title={"新增服饰类型"}
        open={isShow}
        okText="确认"
        cancelText="取消"
        onCancel={close}
        onOk={() => addCloth()}
      >
        <Input
          onChange={(v) => {
            console.log(v.target.value);

            setClouthVal(v.target.value);
          }}
        />
      </Modal>

      <Modal
        maskClosable={false}
        title={"新增公司"}
        open={isShow_a}
        okText="确认"
        cancelText="取消"
        onCancel={close}
        onOk={() => addCampny1()}
      >
        <Input
          onChange={(v) => {
            console.log(v.target.value);
            setCampanyVal(v.target.value);
          }}
        />
      </Modal>

      <Modal
        maskClosable={false}
        title={"新增人员"}
        open={isShow_b}
        okText="确认"
        cancelText="取消"
        onCancel={close}
        onOk={()=>handleAdd('add')}
      >
        <Form
          form={form}
          name="validateOnly"
          layout="vertical"
          autoComplete="off"
        >
          <Form.Item name="name" label="姓名" rules={[{ required: true }]}>
            <Input />
          </Form.Item>
          <Form.Item name="age" label="年龄" rules={[{ required: true }]}>
            <InputNumber min={1} max={100} />
          </Form.Item>
          <Form.Item name="phone" label="电话号码" rules={[{ required: true }]}>
            <Input />
          </Form.Item>
          <Form.Item name="address" label="地址">
            <Input />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        maskClosable={false}
        title={"扁你人员信息"}
        open={isShow_c}
        okText="确认"
        cancelText="取消"
        onCancel={close}
        onOk={()=>handleAdd2('edit')}
      >
        <Form
          form={form1}
          name="validateOnly"
          layout="vertical"
          autoComplete="off"
        >
          <Form.Item name="name" label="姓名" rules={[{ required: true }]}>
            <Input />
          </Form.Item>
          <Form.Item name="age" label="年龄" rules={[{ required: true }]}>
            <InputNumber min={1} max={100} />
          </Form.Item>
          <Form.Item name="phone" label="电话号码" rules={[{ required: true }]}>
            <Input />
          </Form.Item>
          <Form.Item name="address" label="地址">
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
}

whiteConfig.route = { [MENU_PATH]: "/whiteConfig" };
